package com.njwb.sql;

import com.njwb.entity.Dept;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Description: 类的描述
 * Author: yuandeyin@itany.com
 * Date: 2025-08-08 14:44
 * Version: 1.0
 */
public class TestInsertDept {
    public static void main(String[] args) {
        //保存一个Dept对象
        Dept dept = new Dept();
        dept.setDeptNo(30);
        dept.setName("创新组");
        dept.setLoc("L30室");

        //1.加载驱动类
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.获取连接
        //所有的导包都是java.sql
        Connection conn = null;
        PreparedStatement pstmt = null;
        String url = "jdbc:mysql://localhost:3306/db_test?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT";
        try {
            conn = DriverManager.getConnection(url,"root","root");

            //3.获取SQL执行器
            // 单纯的英文问号 代表占位符
            String sql = "insert into dept(deptno,dname,dloc) values(?,?,?)";
            pstmt = conn.prepareStatement(sql);

            //执行前需要将占位符赋值  从左往右  1  2  3  4 。。。N
            pstmt.setInt(1,dept.getDeptNo());
            pstmt.setString(2,dept.getName());
            pstmt.setString(3,dept.getLoc());

            //4.执行SQL
            //INSERT, UPDATE or DELETE;
            int rowCount = pstmt.executeUpdate();
            //5.得到数据库的反馈
            if(rowCount > 0){
                System.out.println("添加部门成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6.关闭资源
            if(null != pstmt){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null != conn){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
